<script setup lang="ts">
import {ComfyUI, type ServerStatus} from "~/utils/comfyuiApi";

const {$socket} = useNuxtApp()
definePageMeta({
  //布局
  layout: 'landing-layout',
  validate: async (route: any) => {
    return true
  }
})



const headers = [
  {
    title: '服务器名称',
    align: 'start',
    sortable: false,
    key: 'name',
  },
  {
    title: '服务器地址',
    align: 'start',
    sortable: false,
    key: 'http_url',
  },
  {
    title: '服务器状态',
    align: 'start',
    sortable: false,
    key: 'status',
  },
  {
    title: '队列状态（实时）',
    align: 'start',
    key: 'queue',
  },
  {
    title: '启用状态',
    align: 'start',
    key: 'enabled',
  }
]


const serverStatus = ref<ServerStatus[]>([])

const getServerList= async () => {
  serverStatus.value =await ComfyUI.getServerList()
}

onMounted(() => {
  socketInit()
  getServerList()
  //监听serverstatus
  $socket.on('serverstatus', (message: any) => {
    const {type, data} = JSON.parse(message)
    if (type === 'server_status') {
      //将data赋值给
      serverStatus.value = data
    }
    console.log(data)
  })
})

//添加服务器
const dialog = ref(false)
const serverName = ref('')
const serverUrl = ref('')
const addServer = async () => {
  if (!serverName.value || !serverUrl.value) {
    useSnackbarStore().showWarningMessage('请填写完整')
    return
  }
  const res = await Client_POST('draw/server', {
    name: serverName.value,
    http_url: serverUrl.value
  })
  if (res) {
    await getServerList()
    useSnackbarStore().showSuccessMessage('添加成功')
    dialog.value = false
  }
}
//删除服务器
const deleteServer = async (id: string) => {
  const res = await Client_DELETE(`draw/server/${id}`)
  if (res) {
    await getServerList()
    useSnackbarStore().showSuccessMessage('删除成功')
  }
}

//切换服务器的启用和停用状态
const changeServerStatus = async (id: string) => {
  const res = await Client_PATCH(`draw/server/${id}`, {
    enabled: !serverStatus.value.find(item => item._id === id)?.enabled
  })
  if (res) {
    await getServerList()
    useSnackbarStore().showSuccessMessage('修改成功')
  }
}
//获取服务器的状态
const verifyServerStatus = async (id: string) => {
  const res = await Client_GET(`draw/server/verify/${id}`)
  console.log(res)
  if (res) {
    await getServerList()
    useSnackbarStore().showSuccessMessage('刷新成功')
  }
}
//打开修改面板
const handleEditDialogOpen = (item: ServerStatus) => {
  dialog.value = true
  serverName.value = item.name
  serverUrl.value = item.http_url
}

</script>

<template>
  <v-data-table
      :headers="headers"
      :items="serverStatus"
      item-value="name"
      density="compact"
      item-key="name"
  >
    <template v-slot:top>
      <!--      添加服务器-->
      <v-sheet class="pa-3">
        <v-spacer></v-spacer>
        <v-dialog v-model="dialog" persistent max-width="600px">
          <template v-slot:activator="{ props }">
            <v-btn size="small" color="primary" v-bind="props">
              添加服务器
            </v-btn>
          </template>
          <v-card>
            <v-card-title>
              <span class="text-h5">添加服务器</span>
            </v-card-title>
            <v-card-text class="mt-4">
              <v-row>
                <v-col cols="12" sm="4">
                  <v-text-field v-model="serverName" label="服务器名称" required></v-text-field>
                </v-col>
                <v-col cols="12" sm="8">
                  <v-text-field v-model="serverUrl" label="服务器地址" required></v-text-field>
                </v-col>
              </v-row>
              <v-label class="text-red-lighten-2">*名称请勿重复</v-label>
              <br>
              <v-label>*指定的服务器地址必须是一个可以访问的GPU算力服务器地址</v-label>
            </v-card-text>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn color="blue-darken-1" variant="text" @click="dialog = false">
                关闭
              </v-btn>
              <v-btn color="blue-darken-1" variant="text" @click="addServer">
                保存
              </v-btn>
            </v-card-actions>
          </v-card>
        </v-dialog>
      </v-sheet>
    </template>
    <template v-slot:item="{ item }">
      <tr>
        <template v-for="(header, index) in headers" :key="index">
          <td>
          <span v-if="header.key === 'enabled'" class="d-flex align-center">
            <v-chip size="small" rounded class="ma-2" :color="item[header.key] ? 'success' : 'error'">{{
                item[header.key] ? '启用' : '禁用'
              }}</v-chip>
            <v-btn size="small" rounded class="ma-2"
                   :color="item[header.key] ? 'error' : 'success'"
                   @click="changeServerStatus(item._id)">{{ item[header.key] ? '停用' : '启用' }}</v-btn>
            <!--            修改服务器配置信息-->
            <v-btn size="small" rounded class="ma-2" color="info" @click="handleEditDialogOpen(item)">修改</v-btn>
            <v-btn size="small" rounded class="ma-2" color="warning" @click="deleteServer(item._id)">删除</v-btn>
          </span>
            <!--            服务器装填，online 和 offline-->
            <span v-else-if="header.key === 'status'">
            <v-chip size="small" rounded class="ma-2" :color="item[header.key] === 1? 'success' : 'error'">{{
                item[header.key] === 1 ? 'online' : 'offline'
              }}</v-chip>
              <!--              刷新服务器的状态-->
              <v-btn size="small" rounded class="ma-2" color="secondary"
                     @click="verifyServerStatus(item._id)">刷新</v-btn>
          </span>
            <span v-else>{{ item[header.key] }}</span>
          </td>
        </template>
      </tr>
    </template>


  </v-data-table>

</template>

<style scoped lang="scss">

</style>